package org.example.Polls;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

public class CustomTrustStoreSSLSocketFactory {
	
	private String trustStoreFilename;
	private String trustStorePassword;
	
	public CustomTrustStoreSSLSocketFactory(String trustStoreFilename, String trustStorePassword) {
		this.trustStoreFilename = trustStoreFilename;
		this.trustStorePassword = trustStorePassword;
	}
	
	public String getTrustStoreFilename() {
		return trustStoreFilename;
	}

	public void setTrustStoreFilename(String trustStoreFilename) {
		this.trustStoreFilename = trustStoreFilename;
	}

	public String getTrustStorePassword() {
		return trustStorePassword;
	}

	public void setTrustStorePassword(String trustStorePassword) {
		this.trustStorePassword = trustStorePassword;
	}

	public SSLSocketFactory createSSLSocketFactory() throws IOException, NoSuchAlgorithmException, KeyStoreException, CertificateException, KeyManagementException {
		InputStream trustStore = this.getClass().getResourceAsStream(trustStoreFilename);
		if (trustStore == null)
			throw new FileNotFoundException("File not found: "+trustStoreFilename);
		KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
		keyStore.load(trustStore, trustStorePassword.toCharArray());
		trustStore.close();
		
		TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		tmf.init(keyStore);
		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(null, tmf.getTrustManagers(), null);
		return sslContext.getSocketFactory();
	}
}
